package cn.easybuy.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.easybuy.entity.Category;
import cn.easybuy.entity.Page;
import cn.easybuy.entity.Product;
import cn.easybuy.service.ProductService;
import cn.easybuy.service.impl.ProductServiceImpl;
import com.alibaba.fastjson.JSON;
import com.sun.xml.internal.ws.developer.MemberSubmissionAddressing;

import java.io.File;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


@WebServlet("/product")
public class ProductServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter out = resp.getWriter();
		String opr = req.getParameter("opr");
		ProductService ps = new ProductServiceImpl();
		if("findProduct".equals(opr)){
			String pageIndexs = req.getParameter("pageIndex");
			Page page = new Page();
			page.setPageSize(8);
			if(pageIndexs != null){
				page.setPageIndex(new Integer(pageIndexs));
			}
			try {
				page.setPageCount(ps.ProductTotalCount());
				if("pc".equals(req.getParameter("child"))){
					out.print(page.getPageCount());
				}else{
					List<Product> list = ps.findProductList(page);
					String data = JSON.toJSONString(list);
					out.print(data);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			out.flush();
			out.close();
		}
		if("sort".equals(opr)){
			Category ct=new Category();
			ct.setType(Integer.parseInt(req.getParameter("t")));
			try {
			List<Category> arr=ps.findLevel1(ct);
			String data=JSON.toJSONString(arr);
			out.print(data);
			out.flush();
			out.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if("towsort".equals(opr)){
			Category ct=new Category();
			ct.setType(Integer.parseInt(req.getParameter("t")));
			ct.setParentId(Integer.parseInt(req.getParameter("sel")));
			List<Category> arr=null;
			try {
			arr = ps.findLevel1(ct);
			} catch (Exception e) {
				e.printStackTrace();
			}
			String data=JSON.toJSONString(arr);
			out.print(data);
			out.flush();
			out.close();
		}
		if("three".equals(opr)){
			Category ct=new Category();
			ct.setType(Integer.parseInt(req.getParameter("t")));
			ct.setParentId(Integer.parseInt(req.getParameter("sele")));
			try {
				List<Category> arr=ps.findLevel1(ct);
				String data=JSON.toJSONString(arr);
				out.print(data);
				out.flush();
				out.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if("c".equals(opr)){
			int id=Integer.parseInt(req.getParameter("id"));
			int spid=Integer.parseInt(req.getParameter("spid"));
			List<Product>arr=ps.arr(id,spid);
			String data=JSON.toJSONString(arr);
			out.print(data);
			out.flush();
			out.close();
		}
		if("del".equals(opr)){
			int id=Integer.parseInt(req.getParameter("id"));
			int state=Integer.parseInt(req.getParameter("sta"));
			int spid=Integer.parseInt(req.getParameter("spid"));
			int cou=ps.del(id,state,spid);
			out.print(cou);
			out.flush();
			out.close();
			/*if(cou==1){
				resp.sendRedirect("productList.jsp");
			}else{
				resp.sendRedirect("productList.jsp");
			}*/
		}
		if("b".equals(opr)){
		Product pr=new Product();
		String uploadFileName="";
		String fieldName="";
		boolean isMultipart=ServletFileUpload.isMultipartContent(req);
		String uploadFilePath=req.getSession().getServletContext().getRealPath("images/");
		if(isMultipart){
		FileItemFactory factory=new DiskFileItemFactory();
		ServletFileUpload upload=new ServletFileUpload(factory);
		try {
	    @SuppressWarnings("unchecked")
		List<FileItem> items=upload.parseRequest(req);
		Iterator<FileItem> iter =items.iterator();
		while(iter.hasNext()){
				FileItem item=iter.next();
				if(item.isFormField()){
				fieldName=item.getFieldName();
				if(fieldName.equals("sel")){
				pr.setCategoryLevel1(Integer.parseInt(item.getString()));
			}
				if(fieldName.equals("sele")){
				pr.setCategoryLevel2(Integer.parseInt(item.getString()));	
			}if(fieldName.equals("select")){
				pr.setCategoryLevel3(Integer.parseInt(item.getString()));
			}if(fieldName.equals("s")){
				pr.setState(Integer.parseInt(item.getString("UTF-8")));            
			}if(fieldName.equals("dd")){
			    pr.setDescription(item.getString("UTF-8"));
			}if(fieldName.equals("name")){
		   	    pr.setName(item.getString("UTF-8"));
			}if(fieldName.equals("price")){
				pr.setPrice(Float.parseFloat(item.getString("UTF-8")));
			}if(fieldName.equals("kc")){
				pr.setStock(Integer.parseInt(item.getString("UTF-8")));
			}if("inp".equals(fieldName)){
				pr.setId(Integer.parseInt(item.getString("UTF-8")));
			}if("ys".equals(fieldName)){
				pr.setColour(item.getString("UTF-8"));
			}if("gg".equals(fieldName)){
				pr.setSpecification(item.getString("UTF-8"));
			}if("spid".equals(fieldName)){
				pr.setSpecificationid(Integer.parseInt(item.getString("UTF-8")));
			}if("jf".equals(fieldName)){
				pr.setScore(Integer.parseInt(item.getString("UTF-8")));
			}
			if(pr.getFileName()==null){
				if("fi".equals(fieldName)){
					pr.setFileName(item.getString("UTF-8"));
				}	
			}
			}else{
			String fileName=item.getName();
			if(fileName!=null && !fileName.equals("")){
				File fullFile=new File(item.getName());
				File saveFile=new File(uploadFilePath,fullFile.getName());
				item.write(saveFile);
			    uploadFileName=fullFile.getName();
			 /*   if(uploadFileName==""){
			    	fieldName=item.getFieldName();
			    	if(item.equals("fi")){
			    		pr.setFileName(item.getString());
			    	}
			    }*/
				pr.setFileName(uploadFileName);
			}
			}
			}
			} catch (FileUploadException e) {
						e.printStackTrace();
			} catch (Exception e) {
						e.printStackTrace();
			}
			}
			  if(ps.update(pr)>0){
				out.print("alert('修改成功！')");
				resp.sendRedirect("productList.jsp");
			  }else{
				  out.print("alert('修改失败！')");
				resp.sendRedirect("productList.jsp");
			  }
			}	
			}
	
}
